package com.chat.common.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
	private IpUtils() {}

	private static final String X_REAL_IP = "X-REAL-IP" ;

	private static final String X_FORWARDED_FOR = "X-Forwarded-For" ;

	public static String getIpAddr(HttpServletRequest request) {
		String realIp = request.getHeader(X_REAL_IP);
		String xForwarded= request.getHeader(X_FORWARDED_FOR);
		String remoteAddr= request.getRemoteAddr();
		String ip = "" ;
		if(StringUtils.hasText(xForwarded)) { // 代表可能存在多台nginx
			String[] ips = xForwarded.split(",");
			ip = ips[0];
		}else if(StringUtils.hasText(realIp)) {
			ip = realIp ;
		}else {
			ip = remoteAddr ;
		}
		return ip ;
	}
}
